# -*- coding: utf-8 -*-
'''
Created on 2010-03-28

@author: Jarek
'''
from processors.subversion_repo_processor import SubversionProcessor
import pysvn
import logging
from processors.repository_scanner import RepositoryScanner, execute_processing

class SubversionRepoScanner(RepositoryScanner): #pylint: disable-msg=R0903
    """
    Repository scanner for subversion.
    """
    def _add_subversion_repository(self, processors, conf):
        """
        Adds repository from subversion to the list of processors.
        """
        logging.info("Processing " + conf['location'])
        weburl = conf['weburl'] if 'weburl' in conf else None
        flavor = conf['flavor'] if 'flavor' in conf else None
        new_conf = {}
        new_conf.update(conf)
        if weburl is None:
            pass
        elif flavor == 'websvn':
            new_weburl = conf['weburl'] + "listing.php?repname=" + \
                self._reponame + "&path=/" + conf['title']
            new_conf['weburl'] = new_weburl
        elif flavor == 'googlecode':
            pass
        processor = SubversionProcessor(self._settings, self._storepath, \
                                        self._oldpath, new_conf)
        processor.initialize()
        execute_processing(processors, conf, processor)      

    def scan_repo(self, processors, conf):
        """
        Scans repository and finds repositories. Might be more then one in case
        subdirectories parameter is set to True.
        """
        def get_info(realm, username, may_save): #pylint: disable-msg=W0613
            """
            Retrieves information about user/password for subversion.
            """
            return True, conf['login'], conf['password'], True
        def trust(trust_dict):
            """
            Determines that we should always trust the other end.
            """
            return True, trust_dict['failures'], True 
        def is_dir(entry):
            """
            Checks if entry returned from subversion is directory.
            """
            return entry[0]['kind'] == \
              pysvn.node_kind.dir #@UndefinedVariable pylint: disable-msg=E1101 
        
        client = pysvn.Client()
        client.callback_get_login = get_info
        client.callback_ssl_server_trust_prompt = trust  
        subdirectories = conf['subdirectories'] if 'subdirectories' in conf \
            else False
        if subdirectories: 
            lst = client.list(url_or_path=conf['location'], recurse=False, \
                            dirent_fields=pysvn.SVN_DIRENT_KIND)
            # only choose directories not locks
            # skip ROOT -> root is always returned first
            for entry in [i for i in lst if is_dir(i)][1:]: 
                subdir = entry[0]
                subpath = subdir['repos_path'].encode("utf-8")
                while subpath.startswith("/"):
                    subpath = subpath[1:]
                new_conf = {}
                new_conf.update(conf)
                new_conf['location'] = subdir['path'].encode("utf-8")
                new_conf['title'] = subpath
                self._add_subversion_repository(processors, new_conf)
        else:
            self._add_subversion_repository(processors, conf)
